#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);

# Startupscript casetool, part of Sipman.

my $tool = $ARGV[0];
my $action = $ARGV[1];
my $option1 = $ARGV[2];
my $option2 = $ARGV[3];
my $option3 = $ARGV[4];


my $backHeader="black";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $domainDir = $ENV{'SIM_DOMAINDIR'};
my $baseDir = "$domainDir/case";
my $currDir = "$baseDir/current";
my $oldDir = "$baseDir/old";

sub catFile {
  my $output = "";
  my ($file) = @_;
  open FH, $file or $output = "none";
# $output = readline FH;
  $output = <FH>;
  close FH;
  return $output;
}

sub catFileLine {
  my $outPut = "";
  my ($file) = @_;
  open FH, $file or $outPut = "$file";
  $outPut = <FH>;
  close FH;
  chomp($outPut);  # remove the newline
  return $outPut;
}

sub printFileLine {
  my $file = "@_[0]";
  my $varName = "@_[1]";
  my $rest = "@_[2]";
  my $logFile = "@_[3]";
  my $oldVal = catFileLine ("$file");
# print ("Update file=$file, varName=$varName, content:$rest<BR>");
  if ( "$oldVal" ne "$rest" ) {
    open(OUT, ">$file") || die "cannot create $file: $! (file=$file, varName=$varName, rest=$rest)";
    if ( "$logFile" ne "quiet" ) {
      print ("$varName is gewijzigd, oud:$oldVal nieuw:$rest<BR>");
    }
    print OUT $rest;
    close(OUT);
  }
}

sub testParam {
  my $file = "@_[0]";
  my $parameter = "@_[1]";
  my $update = "@_[2]";
  my $noteDir = "@_[3]";
  my $timestamp = time;
  my $result = param("$parameter");
  if ( "$result" eq "" ) {
#   print("cat ");
    $result = &catFileLine("$file");
  } else {
    my $oldVal = &catFileLine("$file");
    if (( "$update" eq "upd" ) and ( "$result" ne "$oldVal" )) { 
      printFileLine("$file","$parameter","$result","quiet");
      makeNote("$noteDir","$parameter changed: $result","$httpUser","$timestamp");
    }
  }
# print("$result $file<BR>");
  return("$result");
}

sub testNameStrict {
  my $testname = "@_[0]";
  my $type = "@_[1]";
  if ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } else {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-]#A#cds;
  }
  #print ("testname=$testname");
  return $testname;
}

sub testMkDir {
  my $dirName = "@_[0]";
  if ( !-d $dirName ) {
    system "mkdir -p $dirName";
  }
}

sub printMainMenu {
  my $fontColor = "#222222";
  print("
    <FONT COLOR=black>List</FONT>
    <A HREF=$httpScriptName?case+listCases+open><FONT COLOR=$fontColor>open</FONT></A>
    <FONT COLOR=white>|</FONT>
    <A HREF=$httpScriptName?case+listCases+close><FONT COLOR=$fontColor>closed</FONT></A>
    <FONT COLOR=white>/</FONT>
    <FONT COLOR=black>Action</FONT>
    <A HREF=$httpScriptName?case+updCase+new+open><FONT COLOR=$fontColor>new</FONT></A>
    </TD></TR></TABLE><CENTER>
        ");
}

sub listCases {
  my $caseType = "@_[0]";
  my $workDir;
  if ( "$caseType" eq "open" ) {
    $workDir = $currDir;
  } else {
    $workDir = $oldDir;
  }
  print("<TABLE BORDER=0 CELLSPACING=0>
           <TR><TD COLSPAN=2>Listing $caseType.</TD></TR>");
    if ( -d $workDir) {
      chdir("$workDir");
      my @cases = <*>;
      my @entries;
  #print("<TR><TD>");
      foreach my $entry (@cases) {
  #       print("= $entry-");
         my $time = (stat $entry)[9];
  #       print("-$time $entry-");
         splice @entries, @entries, 0, "$time $entry"; # opbouwen array

         #$entries[$entry] = "$time $entry";
      }
      @entries = sort(@entries);
      @entries = reverse (@entries);
  #       print("-end-");
  #print("</TD></TR>");
      foreach my $info (@entries) {
        my ( $dummy, $case ) = split(/ /, $info);
        #print("<TR><TD>$case</TD></TR>");
        dispInfo("$workDir","$case","$caseType");
      }
    }
}

sub dispInfo {
  my $workDir = "@_[0]";
  my $case = "@_[1]";
  my $caseType = "@_[2]";
  my $subject = catFileLine("$workDir/$case/subject");
  my $contact = catFileLine("$workDir/$case/contact");
  my $impact = catFileLine("$workDir/$case/impact");
  my $owner = catFileLine("$workDir/$case/owner");
  my $status = catFileLine("$workDir/$case/status");
  my $dateString = printDate($case,"yyyymmdd");
  my $timeString = printDate($case,"hhmmss");
  print("
    <TR VALIGN=top><TD><A HREF=$httpScriptName?case+updCase+$case+$caseType>$dateString</A></TD><TD>$owner</TD>
            </TD><TD>S:</TD><TD><B>$subject</B></TD></TR>
    <TR VALIGN=top><TD ALIGN=right>$timeString</TD><TD></TD><TD>C:</TD><TD>$contact</TD></TR>
    <TR VALIGN=top><TD></TD><TD></TD><TD>I:</TD><TD>$impact</TD></TR>
    <TR VALIGN=top><TD></TD><TD></TD><TD>R:</TD><TD><I>$status</I></TD></TR>
        ");
}

sub makeNote {
  my $workDir = "@_[0]";
  my $note = "@_[1]";
  my $httpUser = "@_[2]";
  my $timestamp = "@_[3]";
  #print("Note $workDir, $note, $httpUser, $timestamp<BR>");
  testMkDir("$workDir");
  printFileLine("$workDir/text","Note","$note","quiet");
  printFileLine("$workDir/httpUser","User","$httpUser","quiet");
  printFileLine("$workDir/timestamp","timestamp","$timestamp","quiet");

}

sub updCase {
  my $caseNo = "@_[0]";
  my $caseType = "@_[1]";
  my $inputWidth = "100";
  if ( "$caseNo" eq "new" ) {
    $caseNo = time;
    testMkDir("$currDir/$caseNo");
    printFileLine("$currDir/$caseNo/owner","Owner","$httpUser");
  }
  my ( $changeAction, $workDir );
  if ( "$caseType" eq "open" ) {
   $changeAction = "close";
    $workDir = "$currDir/$caseNo";
  } else {
    $changeAction = "open";
    $workDir = "$oldDir/$caseNo";
  }
  print("Case $caseNo <A HREF=$httpScriptName?case+moveCase+$caseNo+$changeAction>($changeAction)</A><BR>");
  my $nNum = param("nNum");
  if ( "$nNum" eq "" ) { $nNum = time; }
  my $note = param("note");
  if ( "$note" ne "" ) {
    if ( "$nNum" eq "" ) {
      $nNum = time;
    }
    $note=~s/\r\n/<BR>/g;
    makeNote("$workDir/note-$nNum-Z","$note","$httpUser","$nNum");
  }
  my $baseNoteDir = "$workDir/note-$nNum";
  testParam("$workDir/subject","Subject","upd","$baseNoteDir-A");
  testParam("$workDir/contact","Contact","upd","$baseNoteDir-B");
  testParam("$workDir/impact","Impact","upd","$baseNoteDir-C");
  testParam("$workDir/status","Status","upd","$baseNoteDir-D");
  my $subject = catFileLine("$workDir/subject");
  my $contact = catFileLine("$workDir/contact");
  my $impact = catFileLine("$workDir/impact");
  my $status = catFileLine("$workDir/status");
  my $owner = catFileLine("$workDir/owner");
  if ( "$owner" eq "" ) { printFileLine("$workDir/owner","owner","$httpUser"); }
  print("<TABLE WIDTH=90%>");
  if ( "$caseType" eq "open" ) {
    print("
         <FORM method=post Action=$httpScriptName?case+updCase+$caseNo+$caseType>
         <INPUT NAME=nNum VALUE=\"$nNum\" TYPE=hidden>
         <TR><TD COLSPAN=2 ALIGN=center><INPUT TYPE=submit Value=Update></TD></TR>
         <TR><TD>Subject</TD><TD><INPUT NAME=Subject Size=$inputWidth VALUE=\"$subject\" Type=text></TD></TR>
         <TR><TD>Contact</TD><TD><INPUT NAME=Contact Size=$inputWidth VALUE=\"$contact\" Type=text></TD></TR>
         <TR><TD>Impact</TD><TD><INPUT NAME=Impact Size=$inputWidth VALUE=\"$impact\" Type=text></TD></TR>
         <TR><TD>Status</TD><TD><INPUT NAME=Status Size=$inputWidth VALUE=\"$status\" Type=text></TD></TR>
        ");
    if ( "$note" ne "" ) {
      printNote("$workDir/note-$nNum-Z");
    }
    $note=~s/<BR>/\r/g;
    print("<TR><TD COLSPAN=2>Text</TD></TR>
           <TR><TD COLSPAN=2><TEXTAREA NAME=\"note\" ROWS=8 COLS=$inputWidth>$note</TEXTAREA>
           <TR><TD COLSPAN=2 ALIGN=center><INPUT TYPE=submit Value=Update></TD></TR>
           </FORM>
          ");
  } else {
    print("
      <TR><TD>Subject</TD><TD>$subject</TD></TR>
      <TR><TD>Contact</TD><TD>$contact</TD></TR>
      <TR><TD>Impact</TD><TD>$impact</TD></TR>
      <TR><TD>Status</TD><TD>$status</TD></TR>
      <TR><TD COLSPAN=2><HR></TD></TR>
      ");

  }
  my @notes = <$workDir/note-*>;
  my $numNotes = @notes;
  #print("num=$numNotes");
  while ( $numNotes >= 0 ) {
    my $timestamp = catFileLine("$notes[$numNotes]/timestamp");
    #print(" $numNotes");
    if (( "$timestamp" eq "$nNum" ) and ( "$caseType" eq "open" )) {
      my $skip = "yes";
    } elsif ( "$timestamp" ne "" ) {
      printNote("$notes[$numNotes]");
    } elsif ( "$notes[$numNotes]" ne "" ) {
      print("<TR><TD COLSPAN=2>Removing dir:$numNotes ($notes[$numNotes])</TD></TR>");
      system("rmdir $notes[$numNotes]");
    }
    $numNotes --;
  }
  
}
sub printDate {
  my $timestamp = "@_[0]";
  my $type = "@_[1]";
  my ($sec,$min,$hour,$mday,$mon,$jaar,$wday,$yday,$isdst) = localtime($timestamp);
  my @z2 = ('00' .. '60');
  $mon++;
  $jaar = $jaar + 1900;
  if ( "$type" eq "yyyymmdd" ) {
    return("$jaar\-$z2[$mon]\-$z2[$mday]");
  } elsif ( "$type" eq "hhmmss" ) {
    return("$z2[$hour]\:$z2[$min]\:$z2[$sec]");
  } else {
    return("$jaar\-$z2[$mon]\-$z2[$mday] $z2[$hour]\:$z2[$min]\:$z2[$sec]");
  }
}

sub printNote {
  my $workDir = "@_[0]";
  my $httpUser = catFileLine("$workDir/httpUser");
  my $text = catFileLine("$workDir/text");
  my $timestamp = catFileLine("$workDir/timestamp");
  my $dateString = printDate($timestamp);
  print("
         <TR><TD COLSPAN=2><B>
         $dateString $httpUser
         </B></TD></TR>
         <TR><TD></TD><TD>$text</TD></TR>
        ");
}

sub moveCase {
  my $caseNo = "@_[0]";
  my $mvDir = "@_[1]";
  my ( $fromDir, $toDir );
  if ( "$mvDir" eq "close" ) {
    $fromDir = $currDir;
    $toDir = $oldDir;
    testMkDir("$oldDir");
  } else {
    $fromDir = $oldDir;
    $toDir = $currDir;
  }
  system("mv $fromDir/$caseNo $toDir");
  listCases("$mvDir");
}

# ------------------------------------- Main ---------------------------------------

&printMainMenu;
print("<CENTER>");
if ( "$action" eq "none" ) {
  listCases("open");
} elsif ( "$action" eq "listCases" ) {
  listCases($option1);
} elsif ( "$action" eq "updCase" ) {
  updCase($option1, $option2);
} elsif ( "$action" eq "moveCase" ) {
  moveCase($option1, $option2);
} else {
  print("Oops, donot know what to do ($action)");
}
print("</TABLE>");
#&printFooter;
